package com.shunde.xunjian.service.impl;

import com.google.gson.Gson;
import com.shunde.xunjian.entity.ruoyi.*;
import com.shunde.xunjian.entity.ruoyi.Params.UserDept;
import com.shunde.xunjian.mapper.ruoyi.*;
import com.shunde.xunjian.util.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class RuoyiServiceImpl {

    @Autowired
    private RuoyiMapper ruoyiMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysPostMapper sysPostMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserPostMapper sysUserPostMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private RedisServiceImpl redisService;

    @Value("${spring.redis.session-outime}")
    private int maxTime;

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    public ResponseEntity<Object> LoginIn(String username, String password) {
        ResponseEntity.BodyBuilder responseBuilder = ResponseEntity.ok();

        Map<String, Object> map = new HashMap<>();

        SysUser sysUser = ruoyiMapper.selectUserByName(username);
        if (sysUser == null) {
            map.put("msg", "用户名不存在!");
            map.put("code", -1);
            return responseBuilder.body(map);
        } else if (!matchesPassword(password, sysUser.getPassword())) {
            map.put("msg", "密码错误!");
            map.put("code", -1);
            return responseBuilder.body(map);
        } else {
            UserInfo userInfo = userInfoMapper.getUserInfo(sysUser.getUserId());
            Gson gson = new Gson();
            String userStr = gson.toJson(userInfo);
            String token = UUID.randomUUID().toString();
            redisService.setKeyWithExpire(token, userStr, maxTime);

            Map<String, Object> body = new HashMap<>();
            body.put("token", token);
            body.put("user", userInfo);
            map.put("code", 200);
            map.put("msg", "登录成功");
            map.put("body", body);

            // 添加cookie数据到响应头
            responseBuilder.header("Set-Cookie", "token=" + token);
            // 返回响应体
            return responseBuilder.body(map);
        }

    }

    /**
     * 登出
     *
     * @param token
     * @return
     */
    public boolean LoginOut(String token) {
        return redisService.delKey(token);
    }

    /**
     * 密码验证
     *
     * @param rawPassword
     * @param encodedPassword
     * @return
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }




    /**
     * 获取所有用户
     *
     * @return
     */
    public Object getUsers() {

        //初始化岗位id对岗位名称的字典
        List<SysPost> sysPosts = sysPostMapper.selectList(null);
        HashMap<Long, String> postIdName = new HashMap<>();
        for (SysPost sysPost:sysPosts
        ) {
            postIdName.put(sysPost.getPostId(),sysPost.getPostName());
        }
        //初始化角色id对角色名称的字典
        List<SysRole> sysRoles = sysRoleMapper.selectList(null);
        HashMap<Long, String> roleIdName = new HashMap<>();
        for (SysRole sysRole:sysRoles
        ) {
            roleIdName.put(sysRole.getRoleId(),sysRole.getRoleName());
        }

        //查询数据
        List<UserDept> userDeptS = userInfoMapper.getUserDept();
        List<SysUserPost> sysUserPosts = sysUserPostMapper.selectList(null);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(null);

        //整合数据

        HashMap<Long, UserDept> objectObjectHashMap = new HashMap<>();
        for (UserDept userDept:userDeptS){
            userDept.setPostNameS(new ArrayList<>());
            userDept.setRoleNameS(new ArrayList<>());
            objectObjectHashMap.put(userDept.getUserId(),userDept);
        }

        for (SysUserPost sysUserPost:sysUserPosts){
            try {
                if(objectObjectHashMap.containsKey(sysUserPost.getUserId())){
                    List<String> postNameS = objectObjectHashMap.get(sysUserPost.getUserId()).getPostNameS();
                    if (postIdName.containsKey(sysUserPost.getPostId())){
                        String s = postIdName.get(sysUserPost.getPostId());
                        postNameS.add(s);
                    }
                    objectObjectHashMap.get(sysUserPost.getUserId()).setPostNameS(postNameS);
                }
            } catch (Exception e) {}
        }

        for (SysUserRole sysUserRole:sysUserRoles){
            try {
                if(objectObjectHashMap.containsKey(sysUserRole.getUserId())){
                    List<String> roleNameS = objectObjectHashMap.get(sysUserRole.getUserId()).getRoleNameS();
                    if (roleIdName.containsKey(sysUserRole.getRoleId())){
                        String s = roleIdName.get(sysUserRole.getRoleId());
                        roleNameS.add(s);
                    }
                    objectObjectHashMap.get(sysUserRole.getUserId()).setRoleNameS(roleNameS);
                }
            } catch (Exception e) {}
        }

        ArrayList<UserDept> newUserDeptS = new ArrayList<>();
        for (Map.Entry<Long, UserDept> entry : objectObjectHashMap.entrySet()) {
            UserDept value = entry.getValue(); // 获取值
            newUserDeptS.add(value);
        }

        return Results.success(newUserDeptS);
    }


}
